package com.bjc.platform.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bjc.platform.model.AdmAuthority;
import com.bjc.platform.model.AdmMenu;
import com.bjc.platform.model.AdmRole;
import com.bjc.platform.model.CustomUserDetails;
import com.bjc.platform.service.AdmMenuService;
import com.bjc.platform.service.AdmRoleService;
import com.bjc.platform.service.AdmUserService;
import com.bjc.platform.util.JSONResult;
import com.bjc.platform.util.StaticMethod;
import com.bjc.platform.vo.ExtTreeModel;

@Controller
@RequestMapping("/role")
public class AdmRoleController extends BaseController {
	@Autowired
	private AdmRoleService admRoleService;

	@Autowired
	AdmUserService admUserService;

	@Autowired
	AdmMenuService admMenuService;

	@RequestMapping(value = "/query", method = RequestMethod.GET)
	@ResponseBody
	public Object query(@RequestParam HashMap<String, Object> reqParam) {
		Long userId = StaticMethod.object2Long(reqParam.get("id"));
		List<Map<String, Object>> roles = admRoleService
				.getAllWithUserId(userId);
		JSONResult result = StaticMethod.TOListJSONResult(true, roles,
				roles.size());
		return result.getJSONResult();
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Object save(@RequestParam HashMap<String, Object> reqParam) {
		CustomUserDetails user = StaticMethod.getUser();
		AdmRole role = new AdmRole();
		String sid = String.valueOf(reqParam.get("id"));
		String name = String.valueOf(reqParam.get("roleName"));
		String sdesc = String.valueOf(reqParam.get("discription"));
		String resIds = String.valueOf(reqParam.get("resIds"));
		Set<AdmAuthority> auths = new HashSet<AdmAuthority>();
		AdmAuthority auth = null;

		if (!StringUtils.isEmpty(sid)) {
			role = admRoleService.get(Long.valueOf(sid));
		} else {
			role = new AdmRole();
			role.setCreator(Long.valueOf(user.getId()));
			role.setCreateTime(new Date());
		}
		role.setDiscription(sdesc);
		role.setRoleName(name);
		role.setAuthorities(null);
		role.setFlag(true);
		int valid = admRoleService.validRoleCheck(role);
		if (AdmRoleService.EXIST_ROLE_NAME == valid) {
			return StaticMethod.TOJSONResult(false, valid).getJSONResult();
		} else {
			Map<String, Boolean> map = new HashMap<String, Boolean>();
			if (!StringUtils.isEmpty(resIds)) {
				String[] resIdArr = resIds.split(",");
				List<AdmMenu> pmenus = admMenuService.getParentMenu(resIdArr);
				if (pmenus != null && pmenus.size() > 0) {
					for (AdmMenu m : pmenus) {
						if (map.get(m.getId()) == null) {
							map.put(m.getId(), true);
							auth = new AdmAuthority();
							auth.setResId(m.getId());
							auth.setFlag(true);
							auth.setCreator(Long.valueOf(user.getId()));
							auth.setCreateTime(new Date());
							auths.add(auth);
						}
					}
					for (String id : resIdArr) {
						if (map.get(id) == null) {
							map.put(id, true);
							auth = new AdmAuthority();
							auth.setResId(id);
							auth.setFlag(true);
							auth.setCreator(Long.valueOf(user.getId()));
							auth.setCreateTime(new Date());
							auths.add(auth);
						}
					}
				}

			}

			role.setAuthorities(auths);
			admRoleService.save(role);

			return StaticMethod.TOJSONResult(true, null).getJSONResult();
		}
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public Object delete(@RequestParam HashMap<String, Object> reqParam) {
		String sid = StaticMethod.object2String(reqParam.get("id"));

		if (!StringUtils.isEmpty(sid)) {
			AdmRole role = admRoleService.get(Long.valueOf(sid));
			if (admUserService.getCountUserByRoleId(role.getId()) == 0) {
				//标记删除
				role.setFlag(false);
				role.setAuthorities(null);
				admRoleService.save(role);
				//admRoleService.delete(role);
				return StaticMethod.TOJSONResult(true, null).getJSONResult();
			} else {
				return StaticMethod.TOJSONResult(false, null).getJSONResult();
			}
		}

		return StaticMethod.TOJSONResult(false, null).getJSONResult();

	}

	/**
	 * @param reqParam
	 * @return
	 */
	@RequestMapping(value = "/getTree", method = RequestMethod.GET)
	@ResponseBody
	public Object getTree() {
		List<AdmRole> roles = admRoleService.getAll();
		ExtTreeModel root = new ExtTreeModel();
		ExtTreeModel child = null;
		List<ExtTreeModel> children = new ArrayList<ExtTreeModel>();
		root.setChildren(children);
		root.setExpanded(true);
		for (AdmRole role : roles) {
			child = new ExtTreeModel();
			child.setText(role.getRoleName());
			child.setLeaf(true);
			child.setCls("");
			children.add(child);
		}
		return root;
	}
}
